//
//  ProductClassify.m
//  cutter
//
//  Created by mac on 15/12/21.
//  Copyright © 2015年 e360. All rights reserved.
//

#import "ProductClassifyCtrl.h"
//局部常量
static const NSString *classifyIdKey = @"id";
static const NSString *classifyNameKey = @"name";
static const NSString *classifyChildKey = @"child";
//
@interface ProductClassifyTipsCell : UIButton
+(CGFloat)makeCells:(id)items view:(UIView*)view width:(CGFloat)width;
@end
@implementation ProductClassifyTipsCell
+(CGFloat)makeCells:(id)items view:(UIView*)view width:(CGFloat)width{
    CGFloat th = 0;
    CGFloat ts = 10;
    CGFloat tx = ts;
    CGFloat ty = ts;
    CGFloat tw = width;
    [view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    //
    for (id gid in items) {
        NSDictionary *group = [items objectForKey:gid];
        NSString *key = [NSString stringWithFormat:@"%@",gid];
        for (NSDictionary *item in group.allValues) {
            ProductClassifyTipsCell *cell = [[ProductClassifyTipsCell alloc] initWithFrame:CGRectZero];
            [cell setTitle:[item objectForKey:classifyNameKey] forState:UIControlStateNormal];
            [cell setTag:[[item objectForKey:classifyIdKey] integerValue]];
            [cell setAccessibilityIdentifier:key];
            [cell sizeToFit];
            //
            CGFloat ch = cell.bounds.size.height + ts;
            CGFloat cw = cell.bounds.size.width + ts;
            if (tx + cw > tw) {
                ty = ty + ch;
                tx = ts;
            }
            //
            [cell setFrame:CGRectMake(tx, ty, cw - ts, ch - ts)];
            [view addSubview:cell];
            tx = tx + cw;
            th = ty + ch;
        }
    }
    return th;
}
-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self setTitleColor:[self color:255 g:255 b:255 f:255] forState:UIControlStateSelected];
        [self setTitleColor:[self color:74 g:74 b:74 f:255] forState:UIControlStateNormal];
        [self.titleLabel setFont:[UIFont systemFontOfSize:14]];
        [self.layer setMasksToBounds:YES];
        [self.layer setCornerRadius:4];
        [self setSelected:NO];
    }
    return self;
}
-(void)setSelected:(BOOL)selected{
    [super setSelected:selected];
    if (selected) {
        [self setBackgroundColor:[self color:71 g:148 b:239 f:255]];
    }else{
        [self setBackgroundColor:[self color:128 g:128 b:128 f:25]];
    }
}
-(UIColor*)color:(CGFloat)r g:(CGFloat)g b:(CGFloat)b f:(CGFloat)f{
    return [UIColor colorWithRed:r / 255.0 green:g / 255.0 blue:b / 255.0 alpha:f / 255.0];
}
-(CGSize)sizeThatFits:(CGSize)size{
    CGSize temp = [self.titleLabel sizeThatFits:size];
    return CGSizeMake(temp.width + 34, temp.height + 26);
}
-(void)layoutSubviews{
    UIImage *img = [self imageForState:self.state];
    if (img) {
        [self setTitleEdgeInsets:UIEdgeInsetsMake(0, -img.size.width, 0, img.size.width)];
        [self setImageEdgeInsets:UIEdgeInsetsMake(0, self.titleLabel.bounds.size.width + 4, 0, -self.titleLabel.bounds.size.width - 4)];
    }
    [super layoutSubviews];
}
@end

//
@interface ProductClassifyTips ()
@property (strong, nonatomic) UIScrollView *scrollView;
@end
@implementation ProductClassifyTips
-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self setScrollView:[[UIScrollView alloc] initWithFrame:CGRectZero]];
        [self.scrollView setBackgroundColor:[UIColor colorWithRed:244.0/255 green:249.0/255 blue:254.0/255 alpha:1]];
        [self addSubview:self.scrollView];
    }
    return self;
}
-(void)showFromRect:(CGRect)frame atView:(UIView*)view{
    [view.layer addAnimation:[CATransition animation] forKey:nil];
    [self.scrollView setFrame:frame];
    [self setFrame:view.bounds];
    [view addSubview:self];
}
-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    UIView *view = [super hitTest:point withEvent:event];
    if (view == self && point.x < self.scrollView.frame.origin.x) {
        return nil;
    }
    return view;
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if ([[touches anyObject] view] == self) {
        if (self.onSelected) {
            self.onSelected(self, nil);
        }
        if (self.superview) {
            [self.superview.layer addAnimation:[CATransition animation] forKey:nil];
            [self removeFromSuperview];
        }
    }
}
-(void)reloadTips{
    NSArray *items = [self.data objectForKey:classifyChildKey];
    NSMutableDictionary *tip = [NSMutableDictionary dictionary];
    for (id item in items) {
        id iid = [item objectForKey:classifyIdKey];
        if(iid){
            [tip setValue:item forKey:iid];
        }
    }
    NSMutableDictionary *tips = [NSMutableDictionary dictionary];
    id gid = [self.data objectForKey:classifyIdKey];
    if (gid) {
        [tips setValue:tip forKey:gid];
    }
    //
    CGFloat th = [ProductClassifyTipsCell makeCells:tips view:self.scrollView width:self.scrollView.frame.size.width];
    [self.scrollView setContentSize:CGSizeMake(self.scrollView.bounds.size.width, th)];
    for (ProductClassifyTipsCell *cell in self.scrollView.subviews) {
        if ([cell isKindOfClass:ProductClassifyTipsCell.class]) {
            [cell addTarget:self action:@selector(cellTouch:) forControlEvents:UIControlEventTouchUpInside];
            [cell setSelected:[self hasTips:cell]];
        }
    }
}
-(void)cellTouch:(ProductClassifyTipsCell*)sender{
    [sender setSelected:!sender.selected];
    if (self.data) {
        id gid = [self.data objectForKey:classifyIdKey];
        NSMutableDictionary *tip = [self.tips objectForKey:gid];
        if (tip == nil ) {
            tip = [NSMutableDictionary dictionary];
            [self.tips setValue:tip forKey:gid];
        }
        //
        NSArray *items = [self.data objectForKey:classifyChildKey];
        for (NSDictionary *item in items) {
            id iid = [item objectForKey:classifyIdKey];
            if (sender.tag == [iid integerValue]) {
                if (sender.selected) {
                    [tip setValue:item forKey:iid];
                }else{
                    if ([tip objectForKey:iid]) {
                        [tip removeObjectForKey:iid];
                    }
                }
                break;
            }
        }
        //
        if (self.onSelected) {
            self.onSelected(self, self.tips);
        }
    }
}
-(BOOL)hasTips:(UIButton*)sender{
    if (self.data) {
        id gid = [self.data objectForKey:classifyIdKey];
        NSDictionary *tips = [self.tips objectForKey:gid];
        if (tips) {
            for (NSDictionary *tip in tips.allValues) {
                if (sender.tag == [[tip objectForKey:classifyIdKey] integerValue]) {
                    return YES;
                }
            }
        }
    }
    return NO;
}
@end


//
@implementation ProductClassifyCell
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
        [self setSelectedBackgroundView:view];
    }
    return self;
}
-(void)setSelectedBackgroundColor:(UIColor *)selectedBackgroundColor{
    [self.selectedBackgroundView setBackgroundColor:selectedBackgroundColor];
}
-(UIColor*)selectedBackgroundColor{
    return [self.selectedBackgroundView backgroundColor];
}
-(void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{
    [super setHighlighted:highlighted animated:animated];
    if (highlighted) {
        [self.nameView setTextColor:self.selectedColor];
    }else{
        [self.nameView setTextColor:self.nomalColor];
    }
}
-(void)setSelected:(BOOL)selected animated:(BOOL)animated{
    [super setSelected:selected animated:animated];
    if (selected) {
        UIColor *color = [UIColor colorWithRed:71.0/255.0 green:148.0/255.0 blue:239.0/255.0 alpha:1];
        self.iconView.blend = color;
        [self.nameView setTextColor:self.selectedColor];
    }else{
        self.iconView.blend = nil;
        [self.nameView setTextColor:self.nomalColor];
    }
}
@end


//
@interface ProductClassifyCtrl ()
@property (nonatomic, strong) UIView *footerView;
@end
@implementation ProductClassifyCtrl
- (void)viewDidLoad{
    [super viewDidLoad];
    self.clearsSelectionOnViewWillAppear = NO;
    [self setFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
    [self.footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
    //
    if (self.navigationController) {
        [self setTitle:[self.data objectForKey:classifyNameKey]];
        if ([self.navigationController.viewControllers firstObject] == self) {
            [self.navigationItem setLeftBarButtonItem:nil];
        }else{
            [self.navigationItem.backBarButtonItem setTarget:self];
            [self.navigationItem.backBarButtonItem setAction:@selector(backTouch:)];
        }
    }
}
- (void)backTouch:(id)sender{
    if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (NSMutableDictionary *)data{
    if (nil == _data) {
        [self setData:[NSMutableDictionary dictionary]];
    }
    return _data;
}
- (NSMutableDictionary *)tips{
    if (nil == _tips) {
        [self setTips:[NSMutableDictionary dictionary]];
    }
    return _tips;
}
-(void)reloadTips{
    NSInteger total = [self.tableView numberOfRowsInSection:0];
    NSInteger count = [[self.data objectForKey:classifyChildKey] count];
    NSArray *indexPaths = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:count inSection:0]];
    if (count != total) {
        [self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
    }else{
        [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
    }
}
//
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger count = [[self.data objectForKey:classifyChildKey] count];
    return count + 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *items = [self.data objectForKey:classifyChildKey];
    if (indexPath.row < items.count) {
        NSDictionary *item = [items objectAtIndex:indexPath.row];
        ProductClassifyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
        [cell setAccessoryType:[item objectForKey:classifyChildKey] == nil ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
        [cell.nameView setText:[item objectForKey:classifyNameKey]];
        if([[item objectForKey:@"all"] boolValue] && self.type==0){
            [cell.iconView setImage:[UIImage imageNamed:@"icon_All_nor.png"]];
        }else{
            [cell.iconView setImage:nil];
            [AppData loadImage:[item objectForKey:@"pic"] view:cell.iconView];
        }
        return cell;
    }
    //标签    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tipsIdentifier"];
    [cell.contentView addSubview:self.footerView];
    [self.footerView setFrame:cell.bounds];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (NO == [self isTipsCell:indexPath] && self.onSelected) {
        NSDictionary *item = [[self.data objectForKey:classifyChildKey] objectAtIndex:indexPath.row];
        self.onSelected(indexPath, item);
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([self isTipsCell:indexPath]) {
        CGFloat th = [ProductClassifyTipsCell makeCells:self.tips view:self.footerView width:tableView.frame.size.width];
        for (UIButton *cell in self.footerView.subviews) {
            if ([cell isKindOfClass:ProductClassifyTipsCell.class]) {
                [cell setImage:[UIImage imageNamed:@"btn_SideBar_Clear_act.png"] forState:UIControlStateNormal];
                [cell addTarget:self action:@selector(tipTouch:) forControlEvents:UIControlEventTouchUpInside];
                [cell setSelected:YES];
            }
        }
        return th;
    }
    return tableView.rowHeight;
}
- (BOOL)isTipsCell:(NSIndexPath*)indexPath{
    NSArray *items = [self.data objectForKey:classifyChildKey];
    if (indexPath.row < [items count]) {
        return NO;
    }
    return YES;
}
- (void)tipTouch:(UIButton*)sender{
    NSMutableDictionary *tmp = [NSMutableDictionary dictionaryWithDictionary:self.tips];
    for (id gid in self.tips) {
        NSString *key = [NSString stringWithFormat:@"%@",gid];
        if ([sender.accessibilityIdentifier isEqualToString:key]) {
            NSMutableDictionary *group = [self.tips objectForKey:gid];
            for (id iid in group) {
                if (sender.tag == [iid integerValue]) {
                    [group removeObjectForKey:iid];
                    [self setTips:tmp];
                    [self reloadTips];
                    //
                    if (self.onSelected) {
                        self.onSelected(nil, nil);
                    }
                    return;
                }
            }
        }
    }
}
@end
